package com.wlc.service.impl;

import com.wlc.mapper.LeaveStatsMapper;
import com.wlc.pojo.LeaveStats;
import com.wlc.service.LeaveStatsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class LeaveStatsServiceImpl implements LeaveStatsService {

    @Autowired
    private LeaveStatsMapper leaveStatsMapper;

    @Override
    public List<LeaveStats> getDeptLeaveStats(String startDate, String endDate) {
        log.info("查询部门请假统计: startDate={}, endDate={}", startDate, endDate);

        if (startDate == null || endDate == null) {
            LocalDate now = LocalDate.now();
            startDate = now.withDayOfMonth(1).toString(); // 本月第一天
            endDate = now.toString();
        }

        return leaveStatsMapper.selectDeptLeaveStats(startDate, endDate);
    }

    @Override
    public List<LeaveStats> getLeaveTypeStats(String startDate, String endDate) {
        log.info("查询请假类型统计: startDate={}, endDate={}", startDate, endDate);

        if (startDate == null || endDate == null) {
            LocalDate now = LocalDate.now();
            startDate = now.minusMonths(1).withDayOfMonth(1).toString(); // 上个月第一天
            endDate = now.withDayOfMonth(1).minusDays(1).toString(); // 上个月最后一天
        }

        return leaveStatsMapper.selectLeaveTypeStats(startDate, endDate);
    }

    @Override
    public List<LeaveStats> getMonthlyLeaveTrend(String year) {
        log.info("查询月度请假趋势: year={}", year);

        if (year == null || year.trim().isEmpty()) {
            year = String.valueOf(LocalDate.now().getYear());
        }

        return leaveStatsMapper.selectMonthlyLeaveTrend(year);
    }

    @Override
    public List<LeaveStats> getPersonalLeaveStats(String startDate, String endDate) {
        log.info("查询个人请假统计: startDate={}, endDate={}", startDate, endDate);

        if (startDate == null || endDate == null) {
            LocalDate now = LocalDate.now();
            startDate = now.withDayOfMonth(1).toString(); // 本月第一天
            endDate = now.toString();
        }

        return leaveStatsMapper.selectPersonalLeaveStats(startDate, endDate);
    }

    @Override
    public List<LeaveStats> getLeaveStatusStats(String startDate, String endDate) {
        log.info("查询请假审批状态统计: startDate={}, endDate={}", startDate, endDate);

        if (startDate == null || endDate == null) {
            LocalDate now = LocalDate.now();
            startDate = now.withDayOfMonth(1).toString(); // 本月第一天
            endDate = now.toString();
        }

        return leaveStatsMapper.selectLeaveStatusStats(startDate, endDate);
    }

    @Override
    public Object getLeaveOverview(String startDate, String endDate) {
        log.info("查询请假综合统计: startDate={}, endDate={}", startDate, endDate);

        if (startDate == null || endDate == null) {
            LocalDate now = LocalDate.now();
            startDate = now.minusMonths(1).withDayOfMonth(1).toString(); // 上个月第一天
            endDate = now.withDayOfMonth(1).minusDays(1).toString(); // 上个月最后一天
        }

        Map<String, Object> result = new HashMap<>();
        result.put("deptStats", getDeptLeaveStats(startDate, endDate));
        result.put("typeStats", getLeaveTypeStats(startDate, endDate));
        result.put("statusStats", getLeaveStatusStats(startDate, endDate));
        result.put("personalStats", getPersonalLeaveStats(startDate, endDate));
        result.put("monthlyTrend", getMonthlyLeaveTrend(String.valueOf(LocalDate.now().getYear())));

        // 计算总请假时长和平均时长
        List<LeaveStats> deptStats = getDeptLeaveStats(startDate, endDate);
        double totalDuration = deptStats.stream()
                .mapToDouble(stats -> stats.getTotalDuration() != null ? stats.getTotalDuration().doubleValue() : 0)
                .sum();
        double avgDuration = deptStats.stream()
                .mapToDouble(stats -> stats.getAvgDuration() != null ? stats.getAvgDuration().doubleValue() : 0)
                .average()
                .orElse(0);

        result.put("totalDuration", Math.round(totalDuration * 10.0) / 10.0);
        result.put("avgDuration", Math.round(avgDuration * 10.0) / 10.0);

        return result;
    }

    @Override
    public boolean deleteLeaveById(Long id) {
        try {
            int result = leaveStatsMapper.deleteLeaveById(id);
            log.info("删除请假记录: id={}, 影响行数={}", id, result);
            return result > 0;
        } catch (Exception e) {
            log.error("删除请假记录失败: id={}, 错误: {}", id, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean deleteLeaveByEmployeeId(Long employeeId) {
        try {
            int result = leaveStatsMapper.deleteLeaveByEmployeeId(employeeId);
            log.info("删除员工请假记录: employeeId={}, 影响行数={}", employeeId, result);
            return result > 0;
        } catch (Exception e) {
            log.error("删除员工请假记录失败: employeeId={}, 错误: {}", employeeId, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean batchDeleteLeave(List<Long> ids) {
        try {
            int result = leaveStatsMapper.batchDeleteLeave(ids);
            log.info("批量删除请假记录: ids={}, 影响行数={}", ids, result);
            return result > 0;
        } catch (Exception e) {
            log.error("批量删除请假记录失败: ids={}, 错误: {}", ids, e.getMessage());
            return false;
        }
    }
}